import request from "@/utils/request"
import router from "@/router/index"
import { asyncRoutes, constantRoutes } from '@/router'
// 引入深拷贝
import _ from 'lodash'
import { Message } from "element-ui"

// 筛选出当前用户的路由
function filtersRoleRoutes(asyncRoutes, routes) {
    return asyncRoutes.filter(item => {
        if (routes.includes(item.path)) {
            if (item.children && item.children.length > 0) {
                item.children = filtersRoleRoutes(item.children, routes)
            }
            return true
        }
    })
}



// 数组去重
function uniqueByFilter(array) {
    return array.filter((item, index, self) => self.indexOf(item) === index);
}

function getRolePath(routesArr) {
    let rolePathArr = []
    routesArr.forEach(item => {
        if (item.pagePath) {
            rolePathArr.push(item.pagePath)
        }
        if (item.childMenuList.length > 0) {
            rolePathArr.push(item.pagePath)
            item.childMenuList.forEach(item => {
                if (item.pagePath) {
                    rolePathArr.push(item.pagePath)
                }
            })
        }
    })
    return rolePathArr
}

export default {
    namespaced: true,
    state: {
        token: JSON.parse(localStorage.getItem('token')) || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
        menu: JSON.parse(localStorage.getItem('menu')),
        menus: JSON.parse(localStorage.getItem('menus'))
    },
    actions: {

    },
    mutations: {
        // 用户登录
        userLogin(state, form) {
            request.post('/user/login', form).then(res => {
                if (res.code == 20000) {
                    // 持久化存储用户token
                    state.token = res.data.token
                    localStorage.setItem('token', JSON.stringify(state.token))
                    // state.menu = constantRoutes
                    // 获取角色的 路由
                    let rolePath = uniqueByFilter(getRolePath(res.data.menuList))
                    let userRoutes = filtersRoleRoutes(_.cloneDeep(asyncRoutes), rolePath)
                    state.menu = [...constantRoutes, ...userRoutes];
                    state.menus = rolePath

                    localStorage.setItem('menu', JSON.stringify(state.menu))
                    localStorage.setItem('menus', JSON.stringify(state.menus))

                    userRoutes.forEach(item => {
                        router.addRoute(item);
                    })

                    router.addRoute({
                        // 任意路由
                        path: '/:pathMatch(.*)*',
                        redirect: '/notfoundpage404',
                        name: 'Any',
                        meta: {
                            title: '任意路由',
                            hidden: true,
                            icon: 'el-icon-s-home'
                        }
                    })

                    router.push('/')
                    this.commit('userStore/getUserInfo')

                } else {
                    Message({
                        type: 'error',
                        message: res.msg
                    })
                }
            })
        },
        // 获取用户信息
        getUserInfo(state) {
            request.get('/user/userInfo').then(res => {
                if (res.code == 20000) {
                    state.userInfo = res.data
                    this.commit('userStore/saveUserInfo')
                    // this.commit('userStore/getRoleMenu')
                }
            })
        },
        // 持久化存储用户信息
        saveUserInfo(state) {
            localStorage.setItem('userInfo', JSON.stringify(state.userInfo))

        },
        // 获取角色菜单
        getRoleMenu(state) {
            request.get(`/menu/menuList`).then(res => {
                if (res.code == 20000) {
                    state.menu = res.data
                    localStorage.setItem('menu', JSON.stringify(state.menu))

                }
            })
        },
        // 修改用户信息
        updateUserInfo(state, obj) {
            request.post('/user/updateMyInfo', obj).then(res => {
                if (res.code == 20000) {
                    this.commit('userStore/getUserInfo')
                    Message({
                        type: 'success',
                        message: '操作成功~'
                    })
                }
            })
        },
        // 修改密码
        updatePassword(state, form) {
            request.post('/user/updatePassword', form).then(res => {
                if (res.code == 20000) {
                    Message({
                        type: 'success',
                        message: '密码修改成功~'
                    })
                } else {
                    Message({
                        type: 'error',
                        message: res.msg
                    })
                }
            })
        },
        // 退出登录
        loginout(state) {
            request.post('/user/logout', {}).then(res => {
                if (res.code == 20000) {
                    state.token = ''
                    state.userInfo = {}
                    localStorage.clear()
                    router.push('/login')
                }
            })
        },
        // 用户注册
        userRegister(state, form) {
            request.post('/user/register', form).then(res => {
                if (res.code == 20000) {
                    Message({
                        type: 'success',
                        message: '用户注册成功'
                    })
                }
            })
        },
    },
    getters: {
    }
}